package com.teacher.game.framework.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.teacher.game.state.DifficultySelectState;

/**
 * 难度偏好管理器
 * 
 * 负责难度选择的持久化存储和恢复，提供用户偏好的长期记忆功能。
 * 支持难度统计分析和个性化推荐。
 * 
 * 存储内容：
 * - 当前选中难度
 * - 各难度游戏次数统计
 * - 各难度最高分记录
 * - 难度偏好分析数据
 * 
 * @version 1.0
 * @since 2025-09-12
 */
public class DifficultyPreferenceManager {
    
    private static final String TAG = "DifficultyPref";
    private static final String PREFS_NAME = "EllioGameDifficulty";
    
    // 存储键名
    private static final String KEY_SELECTED_DIFFICULTY = "selectedDifficulty";
    private static final String KEY_EASY_GAMES = "easyGames";
    private static final String KEY_NORMAL_GAMES = "normalGames";
    private static final String KEY_HARD_GAMES = "hardGames";
    private static final String KEY_EASY_HIGH_SCORE = "easyHighScore";
    private static final String KEY_NORMAL_HIGH_SCORE = "normalHighScore";
    private static final String KEY_HARD_HIGH_SCORE = "hardHighScore";
    private static final String KEY_TOTAL_PLAYTIME = "totalPlaytime";
    private static final String KEY_FIRST_TIME_SETUP = "firstTimeSetup";
    
    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;
    private Context context;
    
    // 缓存数据，避免频繁读取
    private int cachedDifficulty = -1;
    private boolean cacheValid = false;
    
    /**
     * 构造函数
     * @param context Android上下文
     */\n    public DifficultyPreferenceManager(Context context) {\n        this.context = context;\n        this.prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);\n        this.editor = prefs.edit();\n        \n        // 首次运行初始化\n        if (isFirstTimeSetup()) {\n            initializeFirstTime();\n        }\n        \n        Log.d(TAG, \"难度偏好管理器初始化完成\");\n    }\n    \n    /**\n     * 检查是否首次运行\n     */\n    private boolean isFirstTimeSetup() {\n        return !prefs.getBoolean(KEY_FIRST_TIME_SETUP, false);\n    }\n    \n    /**\n     * 首次运行初始化\n     */\n    private void initializeFirstTime() {\n        Log.i(TAG, \"首次运行，初始化难度偏好设置\");\n        \n        // 设置默认难度为一般\n        setSelectedDifficulty(DifficultySelectState.DIFFICULTY_NORMAL);\n        \n        // 初始化统计数据\n        editor.putInt(KEY_EASY_GAMES, 0)\n              .putInt(KEY_NORMAL_GAMES, 0)\n              .putInt(KEY_HARD_GAMES, 0)\n              .putInt(KEY_EASY_HIGH_SCORE, 0)\n              .putInt(KEY_NORMAL_HIGH_SCORE, 0)\n              .putInt(KEY_HARD_HIGH_SCORE, 0)\n              .putLong(KEY_TOTAL_PLAYTIME, 0)\n              .putBoolean(KEY_FIRST_TIME_SETUP, true)\n              .apply();\n        \n        Log.i(TAG, \"首次初始化完成\");\n    }\n    \n    /**\n     * 保存选中的难度\n     * @param difficulty 难度值\n     */\n    public void setSelectedDifficulty(int difficulty) {\n        if (difficulty < DifficultySelectState.DIFFICULTY_EASY || \n            difficulty > DifficultySelectState.DIFFICULTY_HARD) {\n            Log.w(TAG, \"无效的难度值: \" + difficulty);\n            return;\n        }\n        \n        editor.putInt(KEY_SELECTED_DIFFICULTY, difficulty).apply();\n        cachedDifficulty = difficulty;\n        cacheValid = true;\n        \n        Log.d(TAG, \"保存难度: \" + DifficultySelectState.getDifficultyName(difficulty));\n    }\n    \n    /**\n     * 获取选中的难度\n     * @return 难度值\n     */\n    public int getSelectedDifficulty() {\n        if (cacheValid) {\n            return cachedDifficulty;\n        }\n        \n        int difficulty = prefs.getInt(KEY_SELECTED_DIFFICULTY, DifficultySelectState.DIFFICULTY_NORMAL);\n        \n        // 验证数据有效性\n        if (difficulty < DifficultySelectState.DIFFICULTY_EASY || \n            difficulty > DifficultySelectState.DIFFICULTY_HARD) {\n            Log.w(TAG, \"读取到无效难度值: \" + difficulty + \", 重置为一般难度\");\n            difficulty = DifficultySelectState.DIFFICULTY_NORMAL;\n            setSelectedDifficulty(difficulty);\n        }\n        \n        cachedDifficulty = difficulty;\n        cacheValid = true;\n        \n        return difficulty;\n    }\n    \n    /**\n     * 记录游戏次数\n     * @param difficulty 完成的游戏难度\n     */\n    public void recordGamePlayed(int difficulty) {\n        String key;\n        switch (difficulty) {\n            case DifficultySelectState.DIFFICULTY_EASY:\n                key = KEY_EASY_GAMES;\n                break;\n            case DifficultySelectState.DIFFICULTY_NORMAL:\n                key = KEY_NORMAL_GAMES;\n                break;\n            case DifficultySelectState.DIFFICULTY_HARD:\n                key = KEY_HARD_GAMES;\n                break;\n            default:\n                Log.w(TAG, \"无效的游戏难度: \" + difficulty);\n                return;\n        }\n        \n        int currentCount = prefs.getInt(key, 0);\n        editor.putInt(key, currentCount + 1).apply();\n        \n        Log.d(TAG, \"记录游戏次数: \" + DifficultySelectState.getDifficultyName(difficulty) + \n                   \", 总次数: \" + (currentCount + 1));\n    }\n    \n    /**\n     * 更新最高分记录\n     * @param difficulty 游戏难度\n     * @param score 分数\n     * @return 是否创造了新纪录\n     */\n    public boolean updateHighScore(int difficulty, int score) {\n        String key;\n        switch (difficulty) {\n            case DifficultySelectState.DIFFICULTY_EASY:\n                key = KEY_EASY_HIGH_SCORE;\n                break;\n            case DifficultySelectState.DIFFICULTY_NORMAL:\n                key = KEY_NORMAL_HIGH_SCORE;\n                break;\n            case DifficultySelectState.DIFFICULTY_HARD:\n                key = KEY_HARD_HIGH_SCORE;\n                break;\n            default:\n                Log.w(TAG, \"无效的最高分难度: \" + difficulty);\n                return false;\n        }\n        \n        int currentHighScore = prefs.getInt(key, 0);\n        if (score > currentHighScore) {\n            editor.putInt(key, score).apply();\n            Log.i(TAG, \"新的最高分纪录! \" + DifficultySelectState.getDifficultyName(difficulty) + \n                       \": \" + currentHighScore + \" -> \" + score);\n            return true;\n        }\n        \n        return false;\n    }\n    \n    /**\n     * 获取指定难度的游戏次数\n     */\n    public int getGamesPlayed(int difficulty) {\n        String key;\n        switch (difficulty) {\n            case DifficultySelectState.DIFFICULTY_EASY:\n                key = KEY_EASY_GAMES;\n                break;\n            case DifficultySelectState.DIFFICULTY_NORMAL:\n                key = KEY_NORMAL_GAMES;\n                break;\n            case DifficultySelectState.DIFFICULTY_HARD:\n                key = KEY_HARD_GAMES;\n                break;\n            default:\n                return 0;\n        }\n        \n        return prefs.getInt(key, 0);\n    }\n    \n    /**\n     * 获取指定难度的最高分\n     */\n    public int getHighScore(int difficulty) {\n        String key;\n        switch (difficulty) {\n            case DifficultySelectState.DIFFICULTY_EASY:\n                key = KEY_EASY_HIGH_SCORE;\n                break;\n            case DifficultySelectState.DIFFICULTY_NORMAL:\n                key = KEY_NORMAL_HIGH_SCORE;\n                break;\n            case DifficultySelectState.DIFFICULTY_HARD:\n                key = KEY_HARD_HIGH_SCORE;\n                break;\n            default:\n                return 0;\n        }\n        \n        return prefs.getInt(key, 0);\n    }\n    \n    /**\n     * 获取总游戏次数\n     */\n    public int getTotalGamesPlayed() {\n        return getGamesPlayed(DifficultySelectState.DIFFICULTY_EASY) +\n               getGamesPlayed(DifficultySelectState.DIFFICULTY_NORMAL) +\n               getGamesPlayed(DifficultySelectState.DIFFICULTY_HARD);\n    }\n    \n    /**\n     * 获取最喜欢的难度\n     */\n    public int getFavoriteDifficulty() {\n        int easyGames = getGamesPlayed(DifficultySelectState.DIFFICULTY_EASY);\n        int normalGames = getGamesPlayed(DifficultySelectState.DIFFICULTY_NORMAL);\n        int hardGames = getGamesPlayed(DifficultySelectState.DIFFICULTY_HARD);\n        \n        if (easyGames >= normalGames && easyGames >= hardGames) {\n            return DifficultySelectState.DIFFICULTY_EASY;\n        } else if (normalGames >= hardGames) {\n            return DifficultySelectState.DIFFICULTY_NORMAL;\n        } else {\n            return DifficultySelectState.DIFFICULTY_HARD;\n        }\n    }\n    \n    /**\n     * 推荐适合的难度\n     * 基于用户历史表现和游戏次数\n     */\n    public int getRecommendedDifficulty() {\n        int totalGames = getTotalGamesPlayed();\n        \n        // 新手推荐简单难度\n        if (totalGames < 5) {\n            Log.d(TAG, \"新手玩家，推荐简单难度\");\n            return DifficultySelectState.DIFFICULTY_EASY;\n        }\n        \n        // 基于最高分表现分析\n        int easyScore = getHighScore(DifficultySelectState.DIFFICULTY_EASY);\n        int normalScore = getHighScore(DifficultySelectState.DIFFICULTY_NORMAL);\n        int hardScore = getHighScore(DifficultySelectState.DIFFICULTY_HARD);\n        \n        // 如果困难模式有不错的分数，推荐困难\n        if (hardScore > 1000) {\n            Log.d(TAG, \"困难模式表现良好，推荐困难难度\");\n            return DifficultySelectState.DIFFICULTY_HARD;\n        }\n        \n        // 如果一般模式有不错的分数，推荐一般\n        if (normalScore > 500) {\n            Log.d(TAG, \"一般模式表现稳定，推荐一般难度\");\n            return DifficultySelectState.DIFFICULTY_NORMAL;\n        }\n        \n        // 默认推荐简单\n        Log.d(TAG, \"基于表现分析，推荐简单难度\");\n        return DifficultySelectState.DIFFICULTY_EASY;\n    }\n    \n    /**\n     * 添加游戏时间\n     * @param seconds 游戏时长（秒）\n     */\n    public void addPlaytime(long seconds) {\n        long currentPlaytime = prefs.getLong(KEY_TOTAL_PLAYTIME, 0);\n        editor.putLong(KEY_TOTAL_PLAYTIME, currentPlaytime + seconds).apply();\n    }\n    \n    /**\n     * 获取总游戏时间\n     * @return 总游戏时间（秒）\n     */\n    public long getTotalPlaytime() {\n        return prefs.getLong(KEY_TOTAL_PLAYTIME, 0);\n    }\n    \n    /**\n     * 打印统计信息\n     */\n    public void printStatistics() {\n        Log.i(TAG, \"========== 难度统计信息 ==========\");\n        Log.i(TAG, \"当前选择: \" + DifficultySelectState.getDifficultyName(getSelectedDifficulty()));\n        Log.i(TAG, \"推荐难度: \" + DifficultySelectState.getDifficultyName(getRecommendedDifficulty()));\n        Log.i(TAG, \"最爱难度: \" + DifficultySelectState.getDifficultyName(getFavoriteDifficulty()));\n        Log.i(TAG, \"\");\n        \n        Log.i(TAG, \"游戏次数统计:\");\n        Log.i(TAG, \"  简单: \" + getGamesPlayed(DifficultySelectState.DIFFICULTY_EASY) + \"次\");\n        Log.i(TAG, \"  一般: \" + getGamesPlayed(DifficultySelectState.DIFFICULTY_NORMAL) + \"次\");\n        Log.i(TAG, \"  困难: \" + getGamesPlayed(DifficultySelectState.DIFFICULTY_HARD) + \"次\");\n        Log.i(TAG, \"  总计: \" + getTotalGamesPlayed() + \"次\");\n        Log.i(TAG, \"\");\n        \n        Log.i(TAG, \"最高分记录:\");\n        Log.i(TAG, \"  简单: \" + getHighScore(DifficultySelectState.DIFFICULTY_EASY) + \"分\");\n        Log.i(TAG, \"  一般: \" + getHighScore(DifficultySelectState.DIFFICULTY_NORMAL) + \"分\");\n        Log.i(TAG, \"  困难: \" + getHighScore(DifficultySelectState.DIFFICULTY_HARD) + \"分\");\n        Log.i(TAG, \"\");\n        \n        long totalMinutes = getTotalPlaytime() / 60;\n        Log.i(TAG, \"总游戏时长: \" + totalMinutes + \"分钟\");\n        Log.i(TAG, \"===============================\");\n    }\n    \n    /**\n     * 清除所有数据（调试用）\n     */\n    public void clearAllData() {\n        editor.clear().apply();\n        cacheValid = false;\n        Log.w(TAG, \"所有难度偏好数据已清除\");\n    }\n    \n    /**\n     * 导出数据（用于备份或分析）\n     */\n    public String exportData() {\n        StringBuilder sb = new StringBuilder();\n        sb.append(\"EllioGame Difficulty Data Export\\n\");\n        sb.append(\"Selected: \").append(getSelectedDifficulty()).append(\"\\n\");\n        sb.append(\"Easy Games: \").append(getGamesPlayed(DifficultySelectState.DIFFICULTY_EASY)).append(\"\\n\");\n        sb.append(\"Normal Games: \").append(getGamesPlayed(DifficultySelectState.DIFFICULTY_NORMAL)).append(\"\\n\");\n        sb.append(\"Hard Games: \").append(getGamesPlayed(DifficultySelectState.DIFFICULTY_HARD)).append(\"\\n\");\n        sb.append(\"Easy High Score: \").append(getHighScore(DifficultySelectState.DIFFICULTY_EASY)).append(\"\\n\");\n        sb.append(\"Normal High Score: \").append(getHighScore(DifficultySelectState.DIFFICULTY_NORMAL)).append(\"\\n\");\n        sb.append(\"Hard High Score: \").append(getHighScore(DifficultySelectState.DIFFICULTY_HARD)).append(\"\\n\");\n        sb.append(\"Total Playtime: \").append(getTotalPlaytime()).append(\"\\n\");\n        \n        return sb.toString();\n    }\n}